package com.lh.java.javamail;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;
import java.util.Random;
import java.util.StringTokenizer;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.lh.jsp.urlparamEncoding.CharacterEncodingConstants;

public class SendMail {
	private String errmsg = "";
	private ExtendString exstr = new ExtendString();

	private String sender = "";// 发件人地址
	private String smtphost = "";// 邮件发送服务器（smtp）
	private String user = ""; // 登录用户名
	private String password = "";// 登录密码
	private int port;//端口号

	private String subject = "";// mail主题

	public SendMail() {
		this.setpropertiesattri();
	}

	private void setpropertiesattri() {
		try {
			InputStream is = this.getClass().getResourceAsStream(
					"mailserver.properties");
			Properties prop = new Properties();
			prop.load(is);

			this.setSmtphost(prop.get("smtphost").toString());
			this.setUser(prop.get("user").toString());		
			this.setPassword(prop.get("password").toString());
			this.setSender(prop.get("sender").toString());			
			
			this.setSubject(exstr.cs(prop.get("subject").toString()));
		} catch (Exception ex) {
			System.err.println("ex1 in sendmail.java:" + ex.toString());
		}
	}


	public String getErrmsg() {
		return errmsg;
	}

	public void setErrmsg(String errmsg) {
		this.errmsg = errmsg;
	}

	public ExtendString getExstr() {
		return exstr;
	}

	public void setExstr(ExtendString exstr) {
		this.exstr = exstr;
	}

	public String getSender() {
		return sender;
	}

	public void setSender(String sender) {
		this.sender = sender;
	}

	public String getSmtphost() {
		return smtphost;
	}

	public void setSmtphost(String smtphost) {
		this.smtphost = smtphost;
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getSubject() {
		return subject;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	/**
	 * 使用smtp发送邮件 主程序
	 * 
	 * @throws MessagingException
	 *             mail发送失败
	 */
	public void smtp(String receiver, String content) throws MessagingException {
		if (smtphost == null)
			throw new MessagingException("smtphost not found");
		if (user == null)
			throw new MessagingException("user not found");
		if (password == null)
			throw new MessagingException("password not found");

		Properties properties = new Properties();
		properties.put("mail.smtp.host", smtphost);// 设置smtp主机
		properties.put("mail.smtp.auth", "true");// 使用smtp身份验证
		//properties.put("mail.smtp.port", port);// 使用smtp端口验证
		//MyAuth myAuth=new MyAuth(user,password);
		//Session session = Session.getDefaultInstance(properties,myAuth);
		

		Session session = Session.getDefaultInstance(properties,
				new Authenticator() {					
					public PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(user, password);
					}
				});
		//Session session = Session.getDefaultInstance(properties,null);
		session.setDebug(true);

		// 获得邮件会话对象
		MimeMessage mimemsg = new MimeMessage(session);// 创建mime邮件对象
		if (sender != null)// 设置发件人地址
		{
			mimemsg.setFrom(new InternetAddress(sender));
		}
		if (receiver != null)// 设置收件人地址
		{
			mimemsg.setRecipients(Message.RecipientType.TO, parse(receiver));
		}
		if (subject != null)// 设置邮件主题
		{
			Random r = new Random();
			subject="hello";
			subject+=r.nextInt(80000);
			mimemsg.setSubject(subject, com.lh.jsp.urlparamEncoding.CharacterEncodingConstants.UTF8);
		}
		MimeBodyPart part = new MimeBodyPart();// mail内容部分
		part.setText(content == null ? "" : content, com.lh.jsp.urlparamEncoding.CharacterEncodingConstants.UTF8);
		
		// 设置邮件格式为html cqc
		part.setContent(content.toString(), "text/html;charset="+CharacterEncodingConstants.UTF8);
		MimeMultipart multipart = new MimeMultipart();
		multipart.addBodyPart(part);// 在 multipart 中增加mail内容部分
		mimemsg.setContent(multipart);// 增加 multipart 到信息体
		mimemsg.setSentDate(new Date());// 设置发送日期
		Transport.send(mimemsg);// 发送邮件
	}

	/** 解析地址集合字符串 */
	private InternetAddress[] parse(String addressset) throws AddressException {
		ArrayList list = new ArrayList();
		StringTokenizer tokens = new StringTokenizer(addressset, ";");
		while (tokens.hasMoreTokens()) {
			list.add(new InternetAddress(tokens.nextToken().trim()));
		}
		InternetAddress[] addressarray = new InternetAddress[list.size()];
		list.toArray(addressarray);
		return addressarray;
	}

	/**
	 * 供外部调用的接口
	 */

	public boolean sendmails(String mail, String content) {
		int maillen = 0;
		int contentlen = 0;
		if (mail == null || content == null) {
			return false;
		}

		try {
			this.smtp(mail, content);
		} catch (Exception ex) {
			System.err.println("ex2 in sendmail.java:" + ex.toString());
		}

		return true;
	}

	public static void main(String[] args) {
		SendMail mail = new SendMail();
		String email = "529016080@qq.com";
		String content = "sdfasd账号:123 密码:123 <br/>感谢您注册!<br/><a href=http://www.xxxx.com.cn target=_blank>www.xxxx.com.cn</a><br/>此致<br/>xxxx <br/>即日";
		try {
			for(int i=0;i<10;i++){
				mail.sendmails(email, "i am is  "+i+"  "+content);
			}
			
		} catch (Exception ex) {
			System.err.println("ex33:" + ex.toString());
		}
	}
	
	

}
